/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.longview.io.modules.sys.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.longview.io.common.config.Global;
import com.longview.io.common.service.BaseService;
import com.longview.io.common.utils.StringUtils;
import com.longview.io.common.utils.UserAgentUtils;
import com.longview.io.modules.sys.service.SystemService;

/**
 * 手机端视图拦截器
 * @author ThinkGem
 * @version 2014-9-1
 */
public class MobileInterceptor extends BaseService implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		String url = request.getServletPath() ;
		String action = request.getParameter("goodspreview");
		if(url.indexOf("judgesion")>=0&&null==action)
		{
	        HttpSession session = request.getSession(true);  
	        //设置历史浏览URL
	        session.setAttribute(SystemService.SESSION_LOGIN_URL, url.replace("/f/", ""));  
	        // 从session 里面获取用户名的信息  
	        Object obj = session.getAttribute(SystemService.SESSION_NAME_LOGIN_RESULT);  
	        // 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆  
	        if (obj == null || "".equals(obj.toString())) {  
	        	response.sendRedirect(request.getContextPath() + Global.getFrontPath()+"/wx/login.html");
	        	return false;
	        }  
		}		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null){
			// 如果是手机或平板访问的话，则跳转到手机视图页面。
			if(UserAgentUtils.isMobileOrTablet(request) && !StringUtils.startsWithIgnoreCase(modelAndView.getViewName(), "redirect:"))
			{
				
					modelAndView.setViewName("mobile/" + modelAndView.getViewName());
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		
	}

}
